<template>

  <div>
    <!-- <h2>任务名称，提交日期，识别类型，总数量，完成数量，剩余数量，权重，完成日期，状态，操作</h2> -->
    <div style="text-align: left;">
      <el-button icon="el-icon-refresh-right" @click="allrefresh" size="mini">刷新</el-button>
    </div>
    <div class="head-container " style="text-align: left;margin-top: 20px; margin-bottom: 20px;">
      <el-input v-model="selectName" clearable placeholder="输入任务名称搜索" @keydown.enter.native="toQuery" size="small"
                class="filter-item" style="width: auto;"></el-input>
      <el-select v-model="status" clearable class="filter-item" size="small" @keydown.enter.native="toQuery"
                 style="margin-left: 20px;" placeholder="任务状态">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery"
                 style="margin-left: 20px;">搜索
      </el-button>
      <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置
      </el-button>
    </div>
    <template>
      <el-table
        v-loading="loading"
        :element-loading-text="text"
        :data="taskData"
        style="width: 100%"
        align="center"
        @sort-change="onSortChange">
        <el-table-column
          prop="task_name"
          label="任务名称"
          sortable='custom'
          align="center"
          width="160">
        </el-table-column>
        <el-table-column
          prop="weight"
          sortable='custom'
          label="等级"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          sortable='custom'
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          prop="submit_time"
          label="提交日期"
          sortable='custom'
          align="center"
          width="160">
        </el-table-column>
        <el-table-column
          prop="start_time"
          label="开始识别时间"
          sortable='custom'
          align="center"
          width="160">
        </el-table-column>
        <el-table-column
          prop="finish_time"
          sortable='custom'
          label="完成日期"
          align="center"
          width="160">
        </el-table-column>
        <el-table-column
          prop="seconds"
          label="完成时间(秒)"
          align="center"
          width="120">
        </el-table-column>
        <el-table-column
          prop="force_update"
          label="识别类型"
          align="center"
          width="120">
        </el-table-column>
        <el-table-column
          prop="is_num_ocr"
          label="是否数字识别"
          align="center"
          width="120">
        </el-table-column>
        <el-table-column
          prop="json_count"
          label="总数量"
          align="center"
          width="80">
        </el-table-column>
        <el-table-column
          prop="finished_count"
          label="完成数量"
          align="center"
          width="80">
        </el-table-column>
        <el-table-column
          prop="remaining_count"
          label="剩余数量"
          align="center"
          width="80">
        </el-table-column>
        <el-table-column
          prop="save_result_image"
          label="是否保存图片"
          align="center"
          width="120">
        </el-table-column>
        <el-table-column
          label="详情"
          align="center"
          width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="getDetail(scope.row.id,scope.row.save_result_image,scope.row)"
                       :disable="scope.row.status!==0">点击查看
            </el-button>
            <el-dialog
              title="任务详情"
              :append-to-body="true"
              :close-on-click-modal="false"
              :visible.sync="detailDialogVisible"
              width="60%"
              @close="cancelDetail">
              <el-input v-model="selectJsonName" clearable placeholder="输入JSON名称搜索" @keydown.enter.native="toJSONQuery"
                        size="small" class="filter-item" style="width: auto;"></el-input>
              <el-select v-model="jsonStatus" clearable class="filter-item" size="small"
                         @keydown.enter.native="toJSONQuery" style="margin-left: 20px;" placeholder="JSON状态">
                <el-option
                  v-for="item in jsonOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toJSONQuery"
                         style="margin-left: 20px;">搜索
              </el-button>
              <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left"
                         @click="resetJSONQuery">重置
              </el-button>
              <el-table
                :data="taskJsonData"
                style="width: 100%">
                <el-table-column
                  prop="file_name"
                  :show-overflow-tooltip="true"
                  label="JSON名称"
                  width="200"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="file_path"
                  :show-overflow-tooltip="true"
                  label="JSON路径"
                  width="300"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="result_path"
                  :show-overflow-tooltip="true"
                  label="识别结果保存路径"
                  width="300"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="status"
                  label="状态"
                  width="100"
                  align="center">
                </el-table-column>
                <el-table-column label="图片" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" :disabled="getImageDisable(scope.row.status)"
                               @click="getImageBase64(scope.row.id)">加载图片
                    </el-button>
                    <el-image-viewer
                      v-loading="imageloading"
                      v-if="showViewer"
                      :on-close="closeViewer"
                      :url-list="[image_base]"
                    >
                    </el-image-viewer>
                  </template>
                </el-table-column>
                <el-table-column label="识别结果" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" :disabled="getImageDisable(scope.row.status)"
                     @click="toMark(scope.row)">二次识别
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pageutils ref="pageTwo" id="pageTwo" :message="jsonTaskTotalElements" :type=1 @func="getJsonData"/>
            </el-dialog>
          </template>

        </el-table-column>
<!--        fixed="right"-->
        <el-table-column
          label="操作"
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" :disabled="getPauseStatus(scope.row.status)"
                       @click="toPause(scope.row.id)">暂停
            </el-button>
            <el-button type="text" size="small" :disabled="getContinueStatus(scope.row.status)"
                       @click="toContinue(scope.row.id,scope.row.weight)">继续
            </el-button>
            <el-button type="text" size="small" :disabled="getEditStatus(scope.row.status)" @click="toEdit(scope.row)">
              编辑
            </el-button>
            <el-dialog
              title="编辑任务"
              :append-to-body="true"
              :close-on-click-modal="false"
              :visible.sync="editDialogVisible"
              width="30%"
              @close="cancel"
              center>
              <el-form ref="form" :model="form" :rules="rules" size="small" label-width="160px">
                <el-form-item label="任务名称">
                  <el-input v-model="form.taskname" placeholder="请输入任务名称" style="max-width: 250px;"/>
                </el-form-item>
<!--                <el-form-item label="权重">-->
<!--                  <el-input type="number" v-model="form.weight" placeholder="权重越大越优先" style="max-width: 250px;"/>-->
<!--                </el-form-item>-->
                <el-form-item label="识别方式">
                  <el-radio-group v-model="form.ignore">
                    <el-radio label="ignore">忽略已识别过的</el-radio>
                    <el-radio label="force_update">强制更新</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否生成识别结果图片">
                  <el-radio-group v-model="form.generate">
                    <el-radio label="0">否</el-radio>
                    <el-radio label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="editTask" :disabled=" form.weight ==='' || form.taskname === '' ">确
                  定
                </el-button>
              </div>
            </el-dialog>
            <el-button type="text" size="small" @click="toDelete(scope.row.id)">删除</el-button>
            <el-dialog
              title="提示"
              :append-to-body="true"
              :close-on-click-modal="false"
              :visible.sync="deleteDialogVisible"
              width="30%"
              center>
              <span>确认删除任务</span>
              <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteTask">确 定</el-button>
              </span>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
      <pageutils id="pageOne" :message="totalElements" :type=1 @func="getData"/>
    </template>
  </div>
</template>
<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
// import {
//   getTaskList,
//   stopTaskApi,
//   deleteTaskApi,
//   continueTaskApi,
//   editTaskApi,
//   getJsonFilesList,
//   getResultImage,
//   getImagePath
// } from '../service/commonService'
import {
  getTaskList,
  stopTaskApi,
  deleteTaskApi,
  continueTaskApi,
  editTaskApi,
  getJsonFilesList,
  getResultImage,
  getImagePath
} from '../service/common'
import pageutils from './pageutils'

export default {
  name: 'tasklist',
  props: {
    fileList: {}
  },
  components: {
    pageutils,
    ElImageViewer
  },
  data () {
    return {
      task_name: '',  // 查看的图片的任务名称
      imageloading: false,
      showViewer: false,
      image_base: '',
      image_flag: true,
      text: '',
      detailDialogVisible: false,
      loading: false,
      pauseloading: false,
      options: [{
        value: '0',
        label: '等待'
      }, {
        value: '1',
        label: '正在识别'
      }, {
        value: '2',
        label: '识别结束'
      }, {
        value: '3',
        label: '暂停'
      }],
      status: '',
      selectName: '',
      taskData: [],
      requestParams: {
        size: 10,
        page: 1
      },
      requestData: {
        type: '',
        order: '',
        status: '',
        task_name: ''
      },
      totalElements: 0,
      deleteDialogVisible: false,
      editDialogVisible: false,
      form: {
        id: '',
        taskname: '',
        weight: '',
        ignore: 'ignore',
        generate: '1'
      },
      rules: {},
      deleteId: '',
      detailId: '',
      selectJsonName: '',
      jsonStatus: '',
      jsonOptions: [{
        value: '0',
        label: '等待识别'
      }, {
        value: '1',
        label: '正在识别'
      }, {
        value: '2',
        label: '识别结束'
      }, {
        value: '3',
        label: '暂停'
      }],
      taskJsonData: [],
      jsonRequestData: {
        task_id: '',
        file_name: '',
        status: ''
      },
      jsonRequestParams: {
        size: 10,
        page: 1
      },
      jsonTaskTotalElements:0,
      timer:''
    }
  },
  created () {
    // console.log("1")
    this.requestData.type = 'submit_time'
    this.requestData.order = 'desc'
    this.getData([this.requestParams.size, this.requestParams.page])
    this.requestData.type = ''
    this.requestData.order = ''
    // this.getTasks(this.requestParams)
  },
  mounted(){
    this.timer = setInterval(this.refresh,30000)
  },
  destroyed(){
    clearInterval(this.timer)
  },
  methods: {
    getImageDisable (status) {
      // console.log(status)
      if (status !== '识别结束' || !this.image_flag) {
        return true
      } else {
        false
      }
    },
    closeViewer () {
      this.showViewer = false
      this.image_base = ''
    },
    getImageBase64 (id) {
      this.imageloading = true
      this.showViewer = true
      console.log('image_id', id)
      this.getBas64(id)
    },
    toMark(row){
      // console.log("所选json信息",row)
      let data = {}
      data['image_id'] = row.id
      data['taskId'] = this.jsonRequestData.task_id
      data['taskName'] = this.task_name
      data['jsonName'] = row.file_name
      data['jsonPath'] = row.file_path
      data['lastSaveJsonPath'] = row.result_path.split(',')[row.result_path.split(',').length-1]
      let jsonPath = row.file_path
      getImagePath(jsonPath).then(res=>{
        data['imagePath'] = res.data.image_path
        this.$store.state.imageDetail = data
        this.$router.push({
          path: '/marking',
          query:{
            imageData: data
          }
        })
      })
      this.detailDialogVisible = false
    },
    onSortChange ({ prop, order }) {
      console.log('prop,order', prop, order)
      if (prop === 'task_name') {
        this.sortByTaskName(order)
      } else if (prop === 'submit_time') {
        this.sortBySubmitTime(order)
      } else if (prop === 'weight') {
        this.sortByWeight(order)
      } else if (prop === 'status') {
        this.sortByStatus(order)
      } else {
        this.sortByFinishTime(order)
      }
    },
    sortByTaskName (order) {
      console.log('sortByTaskName', order)
      let o = ''
      if (order === 'ascending') {
        o = 'asc'
      } else {
        o = 'desc'
      }
      this.requestData.type = 'task_name'
      this.requestData.order = o
      this.getData([this.requestParams.size, this.requestParams.page])
    },
    sortBySubmitTime (order) {
      console.log('sortBySubmitTime', order)
      let o = ''
      if (order === 'ascending') {
        o = 'asc'
      } else {
        o = 'desc'
      }
      this.requestData.type = 'submit_time'
      this.requestData.order = o
      this.getData([this.requestParams.size, this.requestParams.page])
    },
    sortByWeight (order) {
      console.log('sortByWeight', order)
      let o = ''
      if (order === 'ascending') {
        o = 'asc'
      } else {
        o = 'desc'
      }
      this.requestData.type = 'weight'
      this.requestData.order = o
      this.getData([this.requestParams.size, this.requestParams.page])
    },
    sortByFinishTime (order) {
      console.log('sortByFinishTime', order)
      let o = ''
      if (order === 'ascending') {
        o = 'asc'
      } else {
        o = 'desc'
      }
      this.requestData.type = 'finish_time'
      this.requestData.order = o
      this.getData([this.requestParams.size, this.requestParams.page])

    },
    sortByStatus (order) {
      console.log('sortByStatus', order)
      let o = ''
      if (order === 'ascending') {
        o = 'asc'
      } else {
        o = 'desc'
      }
      this.requestData.type = 'status'
      this.requestData.order = o
      this.getData([this.requestParams.size, this.requestParams.page])
    },
    submitSuccessNotify (msg) {
      this.$notify({
        title: msg,
        type: 'success',
        duration: 2500
      })
    },
    submitFailureNotify (msg, error) {
      this.$notify({
        title: msg + error,
        type: 'error',
        duration: 2500
      })
    },

    resetRequestData () {
      this.requestData = {
        type: '',
        order: '',
        status: '',
        task_name: ''
      }
    },
    toQuery () {
      console.log('toQuery()', this.selectName, this.status)
      this.resetRequestData()
      this.requestData.task_name = this.selectName
      this.requestData.status = this.status
      this.getData([this.requestParams.size, this.requestParams.page])
      // this.requestData.task_name = ''
      // this.requestData.status = ''
    },
    toJSONQuery () {
      this.jsonRequestData.file_name = ''
      this.jsonRequestData.status = ''
      this.jsonRequestData.file_name = this.selectJsonName
      this.jsonRequestData.status = this.jsonStatus
      console.log('toJsonQuery', this.selectJsonName, this.jsonStatus)
      this.getJsonData([this.jsonRequestParams.size, this.jsonRequestParams.page])

    },
    resetQuery () {
      this.status = ''
      this.selectName = ''
    },
    resetJSONQuery () {
      this.selectJsonName = ''
      this.jsonStatus = ''
      console.log('resetJsonQuery', this.selectJsonName, this.jsonStatus)
    },
    allrefresh () {
      this.selectName = ''
      this.status = ''
      this.resetRequestData()
      this.refresh()
    },
    refresh () {
      console.log('refresh')
      // this.resetRequestData()
      this.requestData.type = 'submit_time'
      this.requestData.order = 'desc'
      this.getData([this.requestParams.size, this.requestParams.page])
      this.requestData.type = ''
      this.requestData.order = ''
    },
    cancel () {
      this.resetForm()
    },
    cancelDetail () {
      this.resetDetailFrom()
    },
    resetDetailFrom () {
      this.deleteDialogVisible = false
      this.selectJsonName = ''
      this.jsonStatus = ''
    },
    resetForm () {
      this.editDialogVisible = false
      this.$refs['form'].resetFields()
      this.form = {
        id: '',
        taskname: '',
        weight: '',
        ignore: 'ignore',
        generate: '1'
      }
    },
    getEditStatus (status) {
      if (status === '等待') {
        return false
      } else {
        return true
      }
    },
    getPauseStatus (status) {
      if (status === '正在识别') {
        return false
      } else {
        return true
      }
    },
    getContinueStatus (status) {
      if (status === '暂停' || status === '暂停中') {
        return false
      } else {
        return true
      }
    },
    getDetail (id, flag,row) {
      if (flag === '否') {
        this.image_flag = false
      } else {
        this.image_flag = true
      }
      // console.log("点击详情获得的row",row)
      this.task_name = row.task_name
      this.detailDialogVisible = true
      this.jsonRequestData.task_id = id
      this.getJsons(this.jsonRequestParams, this.jsonRequestData)
    },
    toPause (id) {
      this.loading = true
      this.text = '正在暂停'
      stopTaskApi(id).then((res) => {
        // console.log('返回成功，结果：', res)
        if (res.status === '1') {
          this.submitSuccessNotify('暂停任务成功')
          this.refresh()
          this.pauseloading = false
        } else {
          this.submitFailureNotify('暂停任务失败', '')
          // console.log('11111111', this.dataArr)
        }
      }).catch((error) => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', error)
      })
    },
    toContinue (id, weight) {
      this.loading = true
      this.text = '正在继续'
      continueTaskApi(id, weight).then((res) => {
        // console.log('返回成功，结果：', res)
        if (res.status === '1') {
          this.submitSuccessNotify('继续任务成功')
          setTimeout(() => {
            this.refresh()
            this.loading = false
          }, 1000)

        } else {
          this.submitFailureNotify('继续任务失败', '')
          // console.log('11111111', this.dataArr)
        }
      }).catch((error) => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', error)
      })

    },
    toDelete (id) {
      console.log(id)
      this.deleteDialogVisible = true
      this.deletedId = id
    },
    deleteTask () {
      this.deleteDialogVisible = false
      this.loading = true
      this.text = '正在删除'
      deleteTaskApi(this.deletedId).then((res) => {
        // console.log('返回成功，结果：', res)
        if (res.status === '1') {
          this.submitSuccessNotify('删除任务成功')
          console.log(this)
          setTimeout(() => {
            this.refresh()
            this.loading = false
          })
        } else {
          this.submitFailureNotify('删除任务失败', '')
          // console.log('11111111', this.dataArr)
        }
      }).catch((error) => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', error)
      })

    },
    toEdit (data) {
      console.log(data)
      this.editDialogVisible = true
      this.form.taskname = data.task_name
      this.form.weight = data.weight
      if (data.force_update === '忽略已识别') {
        this.form.ignore = 'ignore'
      } else {
        this.form.ignore = 'force_update'
      }
      this.form.id = data.id
      if (data.save_result_image === '是') {
        this.form.generate = '1'
      } else {
        this.form.generate = '0'
      }
    },
    editTask () {
      this.editDialogVisible = false
      editTaskApi(this.form.id, this.form.taskname, this.form.weight, this.form.ignore, this.form.generate).then((res) => {
        console.log('返回成功，结果：', res)
        if (res.status === '1') {
          this.submitSuccessNotify('编辑任务成功')
          this.refresh()
        } else {
          this.submitFailureNotify('编辑任务失败', '')
          // console.log('11111111', this.dataArr)
        }
      }).catch((error) => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', error)
      })
    },
    getData (data) {
      // console.log("2222222")
      this.requestParams.size = data[0]
      this.requestParams.page = data[1]
      this.getTasks(this.requestParams, this.requestData)
    },
    getTasks (requestParams, requestData) {
      this.loading = true
      this.text = '正在加载'
      //  console.log('requestParams.page,requestParams.size',requestParams.page,requestParams.size)
      getTaskList(requestParams.page, requestParams.size, requestData.type, requestData.order, requestData.status, requestData.task_name).then(res => {
        console.log(res.data.content)
        this.taskData = res.data.content
        // 计算识别时间
        for(let item of this.taskData){
          console.log(item.finish_time)
          if(!item.finish_time||!item.start_time){
            item['seconds'] = "计算中"
          }else {
            var dateBegin = new Date(item.start_time);
            var dateEnd = new Date(item.finish_time);
            var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
            var seconds = dateDiff/1000;
            item['seconds'] = seconds
          }
        }
        console.log("taskData",this.taskData)
        this.totalElements = res.data.totalElements
        setTimeout(() => {
          this.loading = false
        }, 500)

      }).catch(err => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', err)
      })
    },
    getJsonData (data) {
      this.jsonRequestParams.size = data[0]
      this.jsonRequestParams.page = data[1]
      this.getJsons(this.jsonRequestParams, this.jsonRequestData)
      //  console.log(this.jsonRequestParams,this.jsonRequestData)
    },
    getJsons (jsonRequestParams, jsonRequestData) {
      getJsonFilesList(jsonRequestParams.page, jsonRequestParams.size, jsonRequestData.task_id, jsonRequestData.status, jsonRequestData.file_name).then(res => {
        this.taskJsonData = res.data.content
        this.jsonTaskTotalElements = res.data.totalElements
      }).catch(err => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', err)
      })
    },
    getBas64 (id) {
      getResultImage(id).then(res => {
        this.image_base = res.imageBase64
        this.imageloading = false
      }).catch(err => {
        this.submitFailureNotify('fileSel与后端通讯发生错误', err)
      })
    }
  }
}

</script>
<style scoped>
.el-button {
  margin-left: 10px;
}
</style>
